from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from notifications.models import Notification
from django.contrib.auth.decorators import login_required


# 消息通知
def my_notifications(request):
    context = {}
    return render(request, 'my_notifications/my_notifications.html', context)


def read_my_notification(request, my_notification_pk):
    my_notification = get_object_or_404(Notification, pk=my_notification_pk)
    my_notification.unread = False
    my_notification.save()

    return redirect(my_notification.data['url'])

    # try:
    #     return redirect(my_notification.data['url'])
    # except:
    #     return ('页面不存在了！')

def delete_my_read_notifications(request):
    notifications = request.user.notifications.read()
    notifications.delete()
    return redirect(reverse('my_notifications'))


# @login_required(login_url='login')
def mark_all_as_read(request):
    request.universe.user.notifications.mark_all_as_read()
    _next = request.GET.get('next')
    if _next:
        return redirect(_next)
    return redirect('mood')

# 全局 404 处理函数
def page_not_found(request, exception, template_name='404.html'):
    response = render(request, template_name=template_name, context={'error':'访问有误:页面不存在'}, status=404)
    response.status_code = 404
    return response

# 全局 500 处理函数
def page_error(request, template_name='500.html'):
    response = render(request, template_name=template_name, context={'error':'访问有误:服务器错误'}, status=500)
    response.status_code = 500
    return response